package org.phalanx.server.game;

import java.util.ArrayList;
import java.util.Iterator;

import org.phalanx.map.MapCoordinates;
import org.phalanx.messenging.AbstractMessage;

public class PhalanxGameStateMessage extends AbstractMessage {
	private ArrayList<PhalanxUnitState> visibleGameState;
	private ArrayList<MapCoordinates> fieldOfVision;
	private Integer uId;
	private Integer turnId;
	private Integer gameId;
	
	public PhalanxGameStateMessage(){
		this.setMessageHeader("gamestate");
		visibleGameState = new ArrayList<PhalanxUnitState>();
		fieldOfVision = new ArrayList<MapCoordinates>();
	}

	public void setUserId(Integer uId){
		this.setToMessage("userid", uId.toString());
	}
	
	public void setTurn(Integer turnId){
		this.setToMessage("turnid", turnId.toString());
	}
	
	public void setGameId(Integer gameId){
		this.setToMessage("gameid", gameId.toString());
	}
	
	public void setUserGameState(ArrayList<PhalanxUnitState> newState){
		visibleGameState = newState;
		serializeUserGameState();
	}
	
	public void setTimeUntilNextTurn(Long nextTurn){
		if (nextTurn != null){
			this.setToMessage("nextturn", nextTurn.toString());
		}
	}
	
	public void setFieldOfVision(ArrayList<MapCoordinates> fov){
		fieldOfVision = fov;
		serializeFieldOfVision();
	}
	
	private void serializeUserGameState(){
		StringBuffer gStateStr = new StringBuffer();
		
		Iterator<PhalanxUnitState> i = visibleGameState.iterator();
		boolean isNotFirst = false;
		
		while (i.hasNext()){
			PhalanxUnitState oneUnit = i.next();
			
			if (isNotFirst){
				gStateStr.append(":");
			} else {
				isNotFirst = true;
			}
			
			gStateStr.append("{");
			gStateStr.append(oneUnit.getPhalanxUnit());
			gStateStr.append("!");
			gStateStr.append(oneUnit.getUserId());
			gStateStr.append("!");
			gStateStr.append(oneUnit.getUnitId());
			gStateStr.append("!");
			gStateStr.append(oneUnit.getMapCoordinates().getX());
			gStateStr.append("!");
			gStateStr.append(oneUnit.getMapCoordinates().getY());
			gStateStr.append("!");
			gStateStr.append(oneUnit.getHitPoints());
			gStateStr.append("}");
		}
		
		this.setToMessage("gamestate", gStateStr.toString());
	}
	
	private void serializeFieldOfVision(){
		StringBuffer fovStr = new StringBuffer();
		
		Iterator<MapCoordinates> i = fieldOfVision.iterator();
		boolean isNotFirst = false;
		
		while(i.hasNext()){
			MapCoordinates c = i.next();
			
			if (isNotFirst){
				fovStr.append(":");
			} else {
				isNotFirst = true;
			}
			
			fovStr.append("{");
			fovStr.append(c.getX());
			fovStr.append("!");
			fovStr.append(c.getY());
			fovStr.append("}");
		}
		
		this.setToMessage("fov", fovStr.toString());
	}
}
